package com.cskaoyan.controller.wx;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.user.User;
import com.cskaoyan.bean.wxlogin.LoginInfoVo;
import com.cskaoyan.bean.wxlogin.UserInfoBeanVo;
import com.cskaoyan.config.shiro.MallToken;
import com.cskaoyan.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.Map;

/**
 * \* Description:
 * \
 */
@RestController
@RequestMapping("wx/auth")
public class WXLoginController {
    @Autowired
    UserService userService;

    @PostMapping("login")
    public BaseRespVo login(@RequestBody Map<String,String> map) {
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        MallToken token = new MallToken(username, password, "wx");
        Subject subject = SecurityUtils.getSubject();
        //执行登陆的方法
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            return BaseRespVo.fail("用户名错误");
        } catch (IncorrectCredentialsException e) {
            return BaseRespVo.fail("密码错误");
        }
        Serializable id = subject.getSession().getId();

        String usernames = (String) subject.getPrincipal();
        User user = userService.getUser(usernames);
        Byte status = user.getStatus();
        if(status ==1){
            return BaseRespVo.fail("该用户已被禁用");
        }else if(status==2){
            return BaseRespVo.fail("该用户已被注销");
        }


        LoginInfoVo loginInfoVo = new LoginInfoVo();
        UserInfoBeanVo userInfoBeanVo = new UserInfoBeanVo();
        userInfoBeanVo.setNickName(user.getNickname());
        userInfoBeanVo.setAvatarUrl(user.getAvatar());
        loginInfoVo.setToken((String) id);
        loginInfoVo.setUserInfo(userInfoBeanVo);
        return BaseRespVo.ok(loginInfoVo);
    }


    @RequestMapping("logout")
    public BaseRespVo logout() {
        return BaseRespVo.ok();
    }


}
